package com.scuec.groupfive.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scuec.groupfive.entity.*;
import com.scuec.groupfive.mapper.FavoriteMapper;
import com.scuec.groupfive.mapper.MockExamRecordMapper;
import com.scuec.groupfive.service.MockExamRecordService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class MockExamRecordServiceImpl implements MockExamRecordService {

    @Autowired
    private MockExamRecordMapper mockExamRecordMapper;

    @Override
    public List<MockExam> getMockExamRecordsByUserId(Long userId, int page, int size) {
        int offset = page * size;
        return mockExamRecordMapper.getMockExamRecordsByUserId(userId, offset, size);
    }

    @Override
    public List<MockExam> searchMockExamRecords(
            Long userId,
            Date startDate,
            Date endDate,
            String keyword,
            int page,
            int size
    ) {
        int offset = page * size;
        return mockExamRecordMapper.searchMockExamRecords(
                userId,
                startDate,
                endDate,
                keyword,
                offset,
                size
        );
    }

    @Override
    public Map<String, Object> getMockExamRecordDetail(Long examId) {
        // 获取考试基本信息
        MockExam mockExam = mockExamRecordMapper.getMockExamRecordById(examId);
        if (mockExam == null) {
            throw new RuntimeException("模拟考试记录不存在");
        }

        // 获取所有题目关联信息
        List<ExamQuestion> questions = mockExamRecordMapper.getExamQuestionsByExamId(examId);
        List<QuestionInfo> questionInfos = mockExamRecordMapper.getQuestionsByExamId(examId);
        List<ChoiceQuestion> choiceQuestions = mockExamRecordMapper.getChoiceQuestionsByExamId(examId);
        List<FillBlankQuestion> fillBlankQuestions = mockExamRecordMapper.getFillBlankQuestionsByExamId(examId);
        List<SubjectiveQuestion> subjectiveQuestions = mockExamRecordMapper.getSubjectiveQuestionsByExamId(examId);

        // 创建题目ID到详细信息的映射
        // 修改questionInfoMap的创建方式
        Map<Long, QuestionInfo> questionInfoMap = questionInfos.stream()
                .collect(Collectors.toMap(
                        QuestionInfo::getQuestionId,
                        Function.identity(),
                        (existing, replacement) -> existing));

        // 其他映射保持原样或同样添加合并函数
        Map<Long, ChoiceQuestion> choiceQuestionMap = choiceQuestions.stream()
                .collect(Collectors.toMap(
                        ChoiceQuestion::getQuestionId,
                        Function.identity(),
                        (existing, replacement) -> existing));

        Map<Long, FillBlankQuestion> fillBlankQuestionMap = fillBlankQuestions.stream()
                .collect(Collectors.toMap(
                        FillBlankQuestion::getQuestionId,
                        Function.identity(),
                        (existing, replacement) -> existing));

        Map<Long, SubjectiveQuestion> subjectiveQuestionMap = subjectiveQuestions.stream()
                .collect(Collectors.toMap(
                        SubjectiveQuestion::getQuestionId,
                        Function.identity(),
                        (existing, replacement) -> existing));

        // 按题型分类并组装完整题目信息
        List<ExamQuestion> sortedChoiceQuestions = new ArrayList<>();
        List<ExamQuestion> sortedFillBlankQuestions = new ArrayList<>();
        List<ExamQuestion> sortedSubjectiveQuestions = new ArrayList<>();

        for (ExamQuestion question : questions) {
            Long questionId = question.getQuestionId();
            question.setQuestionInfo(questionInfoMap.get(questionId));

            if (question.getQuestionType().equals("single_choice")) {  // 添加选择题处理
                ChoiceQuestion choiceQuestion = choiceQuestionMap.get(questionId);
                question.setChoiceQuestion(choiceQuestion);
                sortedChoiceQuestions.add(question);
            } else if (question.getQuestionType().equals("fill_in_the_blank")) {
                // 填空题处理
                FillBlankQuestion fillBlankQuestion = fillBlankQuestionMap.get(questionId);
                question.setFillBlankQuestion(fillBlankQuestion);

                // 使用 FastJSON 解析 blanks 字段
                try {
                    List<String> blanksList = JSON.parseObject(
                            fillBlankQuestion.getBlanks(),
                            new TypeReference<List<String>>() {}
                    );
                    fillBlankQuestion.setBlanksList(blanksList); // 假设 FillBlankQuestion 有 setBlanksList 方法
                } catch (Exception e) {
                    e.printStackTrace();
                    if (fillBlankQuestion != null) {
                        fillBlankQuestion.setBlanksList(new ArrayList<>()); // 解析失败时设为空列表
                    }
                }
                sortedFillBlankQuestions.add(question);
            } else if (question.getQuestionType().equals("subjective")) {
                // 主观题处理
                question.setSubjectiveQuestion(subjectiveQuestionMap.get(questionId));
                sortedSubjectiveQuestions.add(question);
            }
        }

        // 按题目序号排序
        sortedChoiceQuestions.sort(Comparator.comparing(ExamQuestion::getSequence));
        sortedFillBlankQuestions.sort(Comparator.comparing(ExamQuestion::getSequence));
        sortedSubjectiveQuestions.sort(Comparator.comparing(ExamQuestion::getSequence));

        // 计算各题型得分
        double singleQuestionScore = 5.0; // 每题固定5分

        // 计算选择题得分
        double choiceScore = calculateScore(sortedChoiceQuestions);

        // 计算填空题得分
        double fillBlankScore = calculateScore(sortedFillBlankQuestions);

        // 主观题得分为0
        double subjectiveScore = 0;

        // 封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("examInfo", mockExam);
        result.put("choiceQuestions", sortedChoiceQuestions);
        result.put("fillBlankQuestions", sortedFillBlankQuestions);
        result.put("subjectiveQuestions", sortedSubjectiveQuestions);
        result.put("choiceScore", Math.round(choiceScore * 100) / 100.0);
        result.put("fillBlankScore", Math.round(fillBlankScore * 100) / 100.0);
        result.put("subjectiveScore", subjectiveScore);
        result.put("totalScore", mockExam.getScore());
        result.put("userScore", Math.round((choiceScore + fillBlankScore + subjectiveScore) * 100) / 100.0);

        return result;
    }

    private double calculateScore(List<ExamQuestion> questions) {
        return questions.stream()
                .filter(Objects::nonNull) // 过滤掉可能的 null 对象
                .filter(q -> q.getIsCorrect() != null && q.getIsCorrect()) // 增加对 getIsCorrect() 结果为 null 的检查
                .mapToDouble(q -> 5.0) // 每题固定5分
                .sum();
    }
    // MockExamRecordServiceImpl.java

    // 在类中添加：
    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    @Transactional
    public void toggleFavorite(Long userId, Long questionId, Boolean isFavorite) {
        int status = isFavorite ? 1 : 0;
        favoriteMapper.upsertFavorite(userId, questionId, status);
    }
}